import db from "../models/index.js";
import {Op} from "sequelize";

let companyUser = db.companyUser;
let companyUserDao = {};

// 创建公司用户
companyUserDao.createCompanyUser = async (company_id, role, user_id, t) => {
  return companyUser.create({
    company_id, role, user_id
  }, {transaction: t});
};

// 删除公司用户
companyUserDao.deleteCompanyUser = async (company_id, user_id, t) => {
  return companyUser.destroy({
    where: {
      company_id,
      user_id
    },
    transaction: t
  });
};

// 更新公司用户角色
companyUserDao.updateCompanyUserRole = async (company_id, user_id, role, t) => {
  return companyUser.update({
    role
  }, {
    where: {
      company_id,
      user_id
    },
    transaction: t
  });
};

// 获取公司员工该角色列表
companyUserDao.getCompanyRoleUserList = async (company_id, role, t) => {
  let where = {
    company_id
  };
  if (role) {
    where.role = role;
  }
  return companyUser.findAndCountAll({
    where,
    transaction: t,
    raw: true
  });
};

// 获取公司员工列表
companyUserDao.getCompanyUserList = async (company_id, t) => {
  return companyUser.findAll({
    where: {
      company_id
    },
    transaction: t,
    raw: true
  });
};

// 获取用户所在公司列表
companyUserDao.getCompanyListByUserId = async (user_id, t) => {
  return companyUser.findAll({
    attributes: ['role', 'company_id'],
    where: {
      user_id
    },
    transaction: t,
    raw: true
  });
};

// 获取员工在该公司的角色
companyUserDao.getRoleByUserId = async (company_id, user_id, t) => {
  return companyUser.findOne({
    attributes: ['role'],
    where: {
      company_id,
      user_id
    },
    transaction: t,
    raw: true
  });
};

export default companyUserDao;
